package com.haohuo.util;

import java.time.Instant;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;

/**
 * @Author: pk.zhang
 * @Date: 2020/9/22 15:27
 */
public class DateTimeTraceUtil {

    private static final DateTimeFormatter DEFAULT_FMT = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");

    private static final DateTimeFormatter DATE_FMT = DateTimeFormatter.ofPattern("yyyy-MM-dd");

    /**
     * 获取当前时间
     * @return
     */
    public static String getNowDateTime(){
        return LocalDateTime.now().format(DEFAULT_FMT);
    }

    /**
     * 将字符串转日期成Long类型的时间戳，格式为：yyyy-MM-dd HH:mm:ss
     */
    public static Long convertTimeToLong(String time) {
        LocalDateTime parse = LocalDateTime.parse(time, DEFAULT_FMT);
        return LocalDateTime.from(parse).atZone(ZoneId.systemDefault()).toInstant().toEpochMilli();
    }

    /**
     * 将Long类型的时间戳转换成String 类型的时间格式，时间格式为：yyyy-MM-dd HH:mm:ss
     */
    public static String convertTimeToString(Long time){
        return DEFAULT_FMT.format(LocalDateTime.ofInstant(Instant.ofEpochMilli(time),ZoneId.systemDefault()));
    }

    /**
     * 将字符串转日期成Long类型的时间戳，格式为：yyyy-MM-dd
     */
    public static Long convertDateToLong(String date) {
        LocalDate parse = LocalDate.parse(date, DATE_FMT);
        return LocalDate.from(parse).atStartOfDay().atZone(ZoneId.systemDefault()).toInstant().toEpochMilli();
    }

    /**
     * 根据指定格式化日期为localdate
     *
     * @param date
     * @param format
     * @return
     */
    public static LocalDate dateFormat(String date, String format){
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern(format);
        return LocalDate.parse(date, formatter);
    }

    /**
     * 根据默认格式化日期为localdate
     *
     * @param date
     * @return
     */
    public static LocalDate dateDefaultFormat(String date){
        return LocalDate.parse(date, DATE_FMT);
    }

}
